import { ChangeDetectorRef, Component, OnInit, TemplateRef } from '@angular/core';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { DunHelper } from 'src/app/shared/components/captcha/dun.helper';
import { EACaptchaService } from 'src/app/shared/services/business/captcha.service';
import { SystemService } from '../../../services/system.service';

@Component({
  selector: 'app-buyer-transpower',
  templateUrl: './transpower.component.html'
})
export class BuyerTranspowerComponent implements OnInit {
  count = 0;
  i: any;
  smsVerifyCode = '';
  superPhone = '';
  constructor(
    private modal: NzModalRef,
    public service: SystemService,
    public eACaptchaService: EACaptchaService,
    private dunHelper: DunHelper,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.getPhone();
  }
  getPhone() {
    this.service.request(this.service.$api_get_app_admin_info).subscribe(res => {
      if (res) {
        this.superPhone = res.telephone;
      }
    });
  }
  sure() {
    const params = {
      appUserId: this.i.appUserId,
      smsVerifyCode: this.smsVerifyCode,
      telephone: this.i.telephone
    };
    this.service.request(this.service.$api_set_shift_admin, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('操作成功！');
        this.modal.close(true);
      }
    });
  }
  close() {
    this.modal.destroy();
  }
  /**
   * 获取手机验证码
   */
  sendCode() {
    this.eACaptchaService.request(this.eACaptchaService.$api_getAppLesseeAdminSMVerificationCode).subscribe(res => {
      if (res.success && res.data.code === '1') {
        this.eACaptchaService.msgSrv.success('发送验证码成功');
        this.createInterval();
      } else if (res.data.code === '503046') {
        this.dunHelper.popUp().subscribe(_ => {
          this.createInterval();
          this.dunHelper.destory();
        });
      } else {
        this.eACaptchaService.msgSrv.warning(res.msg);
      }
    });
  }

  private createInterval() {
    this.count = 59;
    interval(1000)
      .pipe(take(60))
      .subscribe(x => {
        this.count = 59 - (x + 1);
        this.cdr.detectChanges();
      });
  }
}
